<?php
namespace app\tree\service;
use app\tree\model\PlantModel;
use app\tree\validata\TreeValidata;
use app\base\service\BaseService;
use think\facade\Log;
//树种植service类
class PlantService extends BaseService 
{

	 protected $plant ='';
	 protected $tv='';
	 public function __construct()
	 {
	 	parent::__construct();

	 	$this->plant = new PlantModel;
	 	$this->tv = new TreeValidata;
	 	return $this->return_code();	
	 }
	 //种植树列表功能 树名，树的能量值，树的图片，奖品。需要连表暂时没有
	 protected function tree_list($data){ 
	 	if (!$this->tv->scene('tree_list')->check($data)) {
            return $this->return_code(300,$this->tv->getError());
        }
        return $this->return_code(200,'获取数据成功',$this->plant->tree_list($data));
        
	 }
	 //树种植功能 
	 protected function tree_planting($data){
	 	if (!$this->tv->scene('treesid')->check($data)) {
            return $this->return_code(300,$this->tv->getError());
        }
         
        $data['Userid']=$this->user['Userid'];
        $where_is['token']=$data['Token'];
        $where_is['Iscomplete']=0;
        //判断家庭有没有未完成的树
        $is_true = $this->plant->findByAttributes('plant_trees_user',$where_is,"treeuserid");
        if(!empty($is_true))  return $this->return_code(201,"暂时不能种植新树，因为当前家庭树能量还不足");
        $phase =$this->plant->get_tree_phase($data['treesid']);
        if(empty($phase)) return $this->return_code(400,"树不存在");
        $energy = $this->plant->get_energy($data);//获得当前家庭的实时的能量值
        //计算能量值在哪个阶段
        $treesphase = $this->gradefun($data['treesid'],$energy,$phase);
        //插入表中
        $tree = array('treesid' => $data["treesid"],'token' => $data['Token'],'Cretetime'=>time(),'openid'=>$this->user['Openid'],'Iscomplete'=>0,'treesphase'=>$treesphase,'Userid'=>$this->user['Userid'],'totalenergy'=>$energy);
        if($this->plant->insert('plant_trees_user',$tree)) return $this->return_code(200,"种植成功");
        return $this->return_code();

      
	 }

	 //查看家庭树find_tree
	 protected function find_tree($data){
	 	$data['Token'] = (isset($data['Token'])&&!empty($data['Token'])) ? $data['Token'] :'';
        
	 
	 	$trees = $this->plant->find_tree($data);
	 	return $this->return_code("200","获得数据成功",$trees);
	 }
	 
	 private function gradefun($treesid,$energy,$phase)//树等级函数
	{
		
		$arr =[];
		foreach ($phase as $key => $value) {
			$arr[$value['energy']] = $value['treesphase'];
		}
		//log::write($arr);
	    foreach ($arr as $key => $value)
	    {
	        if ($energy >= $key)
	        {
	        	//log::write("树的等级".$value);
	            return $value;
	        }
	    }
	    
	    return 1;
	}
}